<template>
  <div>
    <div style="margin-top: 60px" class="echart" id="mychart" :style="myChartStyle"></div>
    <div class="input-value">
      <span>横坐标: </span>
      <el-input
        type="textarea"
        v-model="xDataStr"
        placeholder="请输入横坐标"
        maxlength="300"
        @blur="xStr2Array($event)"
      ></el-input>

      <span>纵坐标: </span>
      <el-input
        type="textarea"
        v-model="yDataStr"
        placeholder="请输入纵坐标"
        maxlength="300"
        @blur="yStr2Array($event)"
      ></el-input>
    </div>
    <div class="button-div">
      <el-button class="button1" type="primary" @click="submit">确定</el-button>
      <el-button class="button2" @click="download">下载</el-button>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import html2canvas from 'html2canvas';

export default {
  data() {
    return {
      xData: [],
      yData: [],
      xDataStr: '',
      yDataStr: '',
      myChartStyle: {
        float: 'left',
        width: '100%',
        height: '500px'
      }
    }
  },
  mounted() {
    this.initEcharts();
  },
  methods: {
    // 初始化空的图表
    initEcharts() {
      const chartData = {
        xAxis:{},
        yAxis:{},
        series: [
          {type: 'bar'}
        ]
      };
      const myChart = echarts.init(document.getElementById("mychart"));
      myChart.setOption(chartData);
      window.addEventListener("resize", () => {
        myChart.resize();
      })
    },
    xStr2Array(e) {
      let str = e.target.value.toString()
      let strList = str.split(",")
      this.xData = strList
    },
    yStr2Array(e) {
      let str = e.target.value.toString()
      let strList = str.split(",")
      this.yData = strList
    },
    submit() {
      const myChart = echarts.init(document.getElementById("mychart"));
      myChart.setOption({
        xAxis: {data: this.xData},
        series: [
          {
            data: this.yData
          }
        ]
      });
    },
    download() {
      html2canvas(document.getElementById("mychart")).then(function (canvas) {
        let img = canvas.toDataURL("image/png")
                        .replace("image/png", "image/octet-stream");
        let createIMG = document.createElement("a");
        createIMG.download = "图表.png";
        createIMG.href = img;
        document.body.appendChild(createIMG);
        createIMG.click();
        createIMG.remove();
      });
    }
  }
}

</script>

<style>
.input-value {
  width: 80%;
  margin: 0 auto;
}
.button-div {
  margin-top: 20px;
  text-align: center;
}
</style>
